﻿using System;
using System.Configuration;
using System.IO;
using System.ServiceProcess;
using System.Threading;
using System.Timers;
using Provausio.Server.Nzb.Poller.Logic;
using Provausio.Server.Nzb.Poller.Object.Domain;
using Timer = System.Timers.Timer;

namespace Provausio.Server.Nzb.Poller
{
    public partial class PollStillAlive : ServiceBase
    {
        private readonly PollServicesOperation _pollingOperation;
        private readonly int _pingIntervalSeconds =
            Convert.ToInt32(ConfigurationManager.AppSettings["PingIntervalSeconds"]);


        // ReSharper disable once FieldCanBeMadeReadOnly.Local
        private Timer _pollTimer;

        public PollStillAlive()
        {
            InitializeComponent();
            _pollTimer = new Timer();
            _pollingOperation = new PollServicesOperation();
        }

        public void OnDebug()
        {
            OnStart(null);
        }

        protected override void OnStart(string[] args)
        {
            _pollTimer = new Timer(_pingIntervalSeconds * 1000);
            _pollTimer.Elapsed += On_Tick;

#if DEBUG
            _pollingOperation.PollServices();
#else
            
            _pollTimer.Enabled = true;
#endif

        }

        protected override void OnStop()
        {
            if (_pollTimer != null)
            {
                _pollTimer.Enabled = false;    
            }
        }

        private void On_Tick(object sender, ElapsedEventArgs e)
        {
            // check that network is up
            if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                GenericLogger.WriteLog("!!!!ERROR!!! No network connection was found!");
                return;
            }

            try
            {
                _pollingOperation.PollServices();
            }
            catch(Exception ex)
            {
                var message = string.Format("!!!ERROR!!! {0}", ex.Message);
                GenericLogger.WriteLog(message);
            }
            
        }
    }
}
